package com.fyy.execl.controller;

import com.alibaba.fastjson.JSONObject;
import com.fyy.execl.utils.ExcelUtil;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @Author fyy
 * @Description
 * @Date 2020/12/18 15:03
 */
@RestController
@RequestMapping("/api")
public class ExcelController {

    @Autowired
    private ExcelUtil excelUtil;

    /**
     * 文件导出测试
     * @param fileName 导出文件名称
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam("fileName") String fileName) throws IOException {
        String[] titles = { "编号", "姓名", "年龄"};
        List<LinkedHashMap<String, Object>> datalist = new ArrayList<LinkedHashMap<String, Object>>();
        for(int i = 0;i < 10;i++){
            LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("id", i);
            map.put("name", "ceshi"+i);
            map.put("age", "22222222"+i);
            datalist.add(map);
        }
        CellType[] styles = { CellType.NUMERIC, CellType.STRING, CellType.NUMERIC };
        excelUtil.exportExcel(fileName, titles, datalist, styles, response);
    }

    /**
     * 文件解析测试
     * @param file 导入文件
     */
    @PostMapping("/analExcel")
    public void analExcel(@RequestParam("file") MultipartFile file) throws IOException {
        List<String[]> data = excelUtil.analExcelData(file);
        for(String[] strs : data){
            System.out.println("解析的数据：" + JSONObject.toJSONString(strs));
        }
    }

}
